﻿<%@ WebHandler Language="C#" Class="RbArmyCheckDirInfoHandler" %>
/*Description: 热表军检目录管理
'Copyright (c) : 通力凯顿（北京）系统集成有限公司
'Writer: Zhangrj 
'create Date:20250610
'Rewriter:
'Rewrite Date:
*/
using System;
using System.Web;
using BusinessRule.DTO;
using System.Web.SessionState;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using System.Text;
using System.Linq;
using System.IO;
using Newtonsoft.Json;
using System.Collections.Generic;
using BusinessRule.Business;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using System.Collections;
using NPOI.SS.UserModel;
using Camstar.WebClient.WebServicesProxy.InSiteWebServices;
using BusinessRule.Common;

public class RbArmyCheckDirInfoHandler : IHttpHandler, IRequiresSessionState
{
    CurrentUserInfo m_UserInfo;
    private uLMSCommonBusiness m_CommonObj = new uLMSCommonBusiness();
    string toAppId = System.Configuration.ConfigurationManager.AppSettings["ToAppID_RB"].ToString();////数据中心推送目的ID（热表）
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            string action = context.Request["action"].ToString();
            m_UserInfo = (CurrentUserInfo)context.Session["CurrentUserInfo"];
            if (m_UserInfo == null)
            {
                context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "登录过期，请重新登录" }));
                return;
            }
            switch (action)
            {
                case "GetArmyCheckDirInfoPageData": //获取页面初始化的数据
                    GetArmyCheckDirInfoPageData(context);
                    break;
                case "GetArmyCheckDirInfoList": //获取军检目录列表
                    GetArmyCheckDirInfoList(context);
                    break;
                case "GetSpecInfoByProductId": //通过件号ID获取工序列表
                    GetSpecInfoByProductId(context);
                    break;
                case "SaveArmyCheckDirInfo": //保存军检目录数据
                    SaveArmyCheckDirInfo(context);
                    break;
                case "DeleArmyCheckDirInfo": //删除军检目录
                    DeleArmyCheckDirInfo(context);
                    break;
                default:
                    context.Response.Write(JsonConvert.SerializeObject(new uMESProcessResult() { Result = false, Message = "不存在该功能" }));
                    break;
            }
        }
        catch (Exception ex)
        {
            uMESProcessResult result = new uMESProcessResult();
            result.Result = false;
            result.Message = ex.Message;
            context.Response.Write(JsonConvert.SerializeObject(result));
        }
    }

    /// <summary>
    /// 删除军检目录
    /// </summary>
    /// <param name="context"></param>
    private void DeleArmyCheckDirInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "删除成功！" };
        DataTable dtParam = JsonConvert.DeserializeObject<DataTable>(context.Request["paramDatas"].ToString());
        if (dtParam.Rows.Count == 0)
        {
            result.Result = false; result.Message = "请选择数据！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        ArrayList sqlList = new ArrayList();
        foreach (DataRow item in dtParam.Rows)
        {
            sqlList.Add(string.Format("UPDATE armycheckdirinfo a SET a.isuse = 1 WHERE a.armycheckdirinfoid = '{0}'", item["armycheckdirinfoid"].ToString()));
        }
        sqlList.AddRange(m_CommonObj.InsertSyncTableChangeRecode(dtParam, "armycheckdirinfo", "armycheckdirinfoid", toAppId, 2, false));//同时将删除的数据更新推送工控网
        DatabaseHelper.ExecuteSqlTran(sqlList);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取军检目录的数据
    /// </summary>
    /// <param name="context"></param>
    private void GetArmyCheckDirInfoList(HttpContext context)
    {
        StringBuilder sql = new StringBuilder();
        Dictionary<string, string> dicParam = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["paramDatas"].ToString());
        sql.AppendLine(@"SELECT a.armycheckdirinfoid,a.armyyear,a.partname,a.specno,a.specname,a.createdate
                         FROM armycheckdirinfo a WHERE a.isuse = 0 AND a.branchfactory LIKE '%热表%' AND a.notes = '热表内网申请'");
        if (!string.IsNullOrWhiteSpace(dicParam["years"])) //检测项目
        {
            sql.AppendFormat(" AND a.armyyear = {0}", dicParam["years"]);
        }
        if (!string.IsNullOrWhiteSpace(dicParam["productName"])) //件号
        {
            sql.AppendFormat(" AND a.partname LIKE '%{0}%'", dicParam["productName"]);
        }
        if (!string.IsNullOrWhiteSpace(dicParam["specNo"])) //工序
        {
            sql.AppendFormat(" AND a.specno LIKE '%{0}%'", dicParam["specNo"]);
        }
        sql.AppendLine(" ORDER BY a.createdate DESC, a.partname");
        uMESPagingDataDTO pageDto = new uMESPagingDataDTO();
        pageDto.CurrentPageIndex = int.Parse(dicParam["pageIndex"].ToString());
        pageDto.PageSize = int.Parse(dicParam["pageSize"].ToString());
        pageDto.strSQL = sql.ToString();
        uMESProcessResult result = DatabaseHelper.RunProcedureForPage(pageDto);
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 获取军检目录初始化页面数据
    /// </summary>
    /// <param name="context"></param>
    private void GetArmyCheckDirInfoPageData(HttpContext context)
    {
        /*获取年份下拉*/
        DataTable dtYear = new DataTable();
        dtYear.Columns.Add("year");
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        for (int i = 1; i <= 10; i++)
        {
            dtYear.Rows.Add(DateTime.Now.AddYears(i).Year);
            dtYear.Rows.Add(DateTime.Now.AddYears(-i).Year);
        }
        dtYear.Rows.Add(DateTime.Now.Year);
        DataView dvY = dtYear.AsDataView();
        dvY.Sort = "year";
        dtYear = dvY.ToTable();
        result.DBTable = dtYear;
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    /// <summary>
    /// 保存军检目录数据
    /// </summary>
    /// <param name="context"></param>
    private void SaveArmyCheckDirInfo(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true, Message = "保存成功" };
        StringBuilder sqlBd = new StringBuilder();
        Dictionary<string, string> dicParam = JsonConvert.DeserializeObject<Dictionary<string, string>>(context.Request["paramDatas"].ToString());
        if (string.IsNullOrWhiteSpace(dicParam["productName"]) || string.IsNullOrWhiteSpace(dicParam["specName"])
            || string.IsNullOrWhiteSpace(dicParam["years"]))
        {
            result.Result = false; result.Message = "必填项不能为空！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        dicParam["productName"] = dicParam["productName"].Split(':')[0];//去掉后面的版本和说明
        string specNo = dicParam["specName"].Split('-')[0].PadLeft(4, '0');//工序号
        string specName = dicParam["specName"].Split('-')[1];//工序名
        string querySql = @"SELECT 1 FROM armycheckdirinfo a WHERE a.partname = '{0}' AND a.specno = '{1}' AND a.armyyear = {2} AND a.isuse = 0";
        querySql = string.Format(querySql, dicParam["productName"], specNo, dicParam["years"]);
        if (DatabaseHelper.GetSingle(querySql) != null)
        {
            result.Result = false; result.Message = "已存在相同件号、工序、年份的数据，无法继续添加！";
            context.Response.Write(JsonConvert.SerializeObject(result));
            return;
        }
        /*保存到军检目录表（提示：由于这个表是QMS提供的，所以按照这个表结构存储数据）*/
        string checkId = Guid.NewGuid().ToString();
        sqlBd.AppendLine(@"INSERT INTO armycheckdirinfo(armycheckdirinfoid,partname,specno,specName,armyyear,branchfactory,
                               armychecktype,notes,CreateDate,isuse) VALUES(");
        sqlBd.AppendFormat("'{0}',", checkId);//主键ID
        sqlBd.AppendFormat("'{0}',", dicParam["productName"]);//件号
        sqlBd.AppendFormat("'{0}',", specNo);//工序号
        sqlBd.AppendFormat("'{0}',", specName);//工序名
        sqlBd.AppendFormat("{0},", dicParam["years"]);//年份
        sqlBd.AppendFormat("'{0}',", m_UserInfo.Factory);//分厂
        sqlBd.AppendFormat("'{0}',", "工序军检");//军检类型
        sqlBd.AppendFormat("'{0}',", "热表内网申请");//备注
        sqlBd.AppendLine("sysdate,");//创建时间
        sqlBd.AppendLine("0)");//默认有效
        DatabaseHelper.ExecuteSql(sqlBd.ToString());
        context.Response.Write(JsonConvert.SerializeObject(result));
    }
    /// <summary>
    /// 通过件号ID获取工序列表
    /// </summary>
    /// <param name="context"></param>
    private void GetSpecInfoByProductId(HttpContext context)
    {
        uMESProcessResult result = new uMESProcessResult() { Result = true };
        string sql = string.Format(@"SELECT ws.workflowstepid,s.specno || '-' || s.opdesc specname FROM PRODUCT p
                        LEFT JOIN Workflowbase wb ON wb.workflowbaseid = p.workflowbaseid
                        LEFT JOIN workflow w ON w.workflowid = NVL(wb.revofrcdid,p.workflowid)
                        LEFT JOIN workflowstep ws ON ws.workflowid = w.workflowid
                        LEFT JOIN specbase sb ON sb.specbaseid = ws.specbaseid
                        LEFT JOIN spec s ON s.specid = NVL(sb.revofrcdid,ws.specid)
                        WHERE p.productid = '{0}'
                        ORDER BY ws.sequence", context.Request["productId"].ToString());
        result.DBTable = DatabaseHelper.Query_ReturnDatTable(sql);
        if (result.DBTable.Rows.Count == 0)
        {
            result.Message = "该件号下没有工序！"; result.Result = false;
        }
        context.Response.Write(JsonConvert.SerializeObject(result));
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

}